// example/add_edit/add_edit.js
var app = getApp()
import * as Api from '../../utils/api.js'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    hasGoneAway: false,
    isdefault: false,
    initDefalut:false,
    range: [],
    countryCodeIndex: 1,
    region: ['北京市', '北京市', '东城区'],//下标
    pagetype: '', //页面类型  edit  add
    contactname: '',
    contactmobile: '',
    address: '',
    twoIndex: 0, //bug 第二列不更新  备用第二列下标
    idList: [],
    addressid: ''
  },


  deleteAddress(e) {
    let self = this

    
    wx.showModal({
      title: '提示',
      content: '确定删除该条收货地址？',
      success: function (res) {
        if (res.confirm) {
          let url = app.globalData.baseUrl1 + '/address/delete'

          let data = {
            token: app.globalData.token,
            userId: app.globalData.userId,
            addressId: e.currentTarget.dataset.addressid
          }
          let callBack = (res) => {

            if (res == null) {

              console.log("网络请求错误！");
              return;
            }

            if (res.data.status != 200) {
              console.log("请求数据错误");
              return;
            }
            if (res.data.status == 200) {
              wx.showToast({
                title: '删除成功',
                icon: 'success',
                duration: 2000
              })
              wx: wx.navigateBack({
                delta: 1,
              })

            }
          }
          Api.reqFormPost(url, data, callBack)
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  },
  StringToId() {
    
 let self = this
    if (!self.data.hasGoneAway) {
      self.setData({ hasGoneAway: true })

    if ( this.data.contactname === '' || this.data.contactmobile === '' || this.data.address === '' ){
      self.setData({ hasGoneAway: false })
   
      return
    }


    if (this.data.contactmobile.length!==11 ) {

      wx.showModal({
        title: '',
        content: '联系电话格式错误',
        showCancel: false,
        cancelText: '',
        cancelColor: '',
        confirmText: '知道了',
        confirmColor: '',
        success: function (res) { },
        fail: function (res) { },
        complete: function (res) { },
      })
      self.setData({ hasGoneAway: false })
      
      return;
      
    } 





    let url = app.globalData.baseUrl1 + '/address/querycityid'
    let data = {
      provinceName: self.data.region[0],
      cityName: self.data.region[1],
      countryName: self.data.region[2]
    }

    let callBack = (res) => {
      if (res == null) {
        console.log("网络请求错误！");
        self.setData({ hasGoneAway: false })
        
        return;
      }
      if (res.data.status != 200) {
        self.setData({ hasGoneAway: false })
        
        console.log("请求数据错误");
        return;
      }
      if (res.data.status === 200) {

        console.log(res.data)
        self.data.idList[0] = res.data.data.province.id
        self.data.idList[1] = res.data.data.city.id
        self.data.idList[2] = res.data.data.country.id
        self.setData({
          idList: self.data.idList
        })
        self.ifHaveDefauleAddress()

      }

    }
    Api.reqFormPost(url, data, callBack)
    }
  },
  handleInpue(e) {
    switch (e.currentTarget.dataset.name) {
      case 'contactname':
        this.setData({
          contactname: e.detail.value
        })
        break;
      case 'contactmobile':
        this.setData({
          contactmobile: e.detail.value
        })
        break;
      case 'address':
        this.setData({
          address: e.detail.value
        })
        break;
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    if (app.globalData.merchant === null) {
      app.doLogin(this.onLoad, this.onShow, options);
      return
    }
    let self = this
    this.setData({
      pagetype: options.pagetype
    })
    if (options.pagetype === 'wxadd') {
      let region = [
        options.provinceName,
        options.cityName,
        options.countyName
      ]

      this.setData({
        contactname: options.contactname,
        contactmobile: options.contactmobile,
        address: options.address,
        region: region
      })


    } else if (options.pagetype === 'edit') {
      console.log('-----------')

      let url = app.globalData.baseUrl1 + '/address/queryprovince'
      let data = {}
      let callBack = (res) => {
        if (res == null) {
          console.log("网络请求错误！");
          return;
        }
        if (res.data.status != 200) {
          console.log("请求数据错误");
          return;
        }
        if (res.data.status == 200) {

          for (let i = 0; i < res.data.data.region.length; i++) {
            if (res.data.data.region[i].id === parseInt(options.provinceid)) {
              self.data.region[0] = res.data.data.region[i].name
              self.setData({
                region: self.data.region
              })
            }
          }
          let url = app.globalData.baseUrl1 + '/address/querycity'
          let range = []
          let data1 = []
          data1 = {
            provinceId: options.provinceid
          }
          let callBack = (res1) => {
            if (res1 == null) {
              console.log("网络请求错误！");
              return;
            }
            if (res1.data.status != 200) {
              console.log("请求数据错误");
              return;
            }
            if (res1.data.status === 200) {

              for (let i = 0; i < res1.data.data.region.length; i++) {
                if (res1.data.data.region[i].id === parseInt(options.cityid)) {
                  self.data.region[1] = res1.data.data.region[i].name
                  self.setData({
                    region: self.data.region
                  })
                }
              }
              let url = app.globalData.baseUrl1 + '/address/querycountry'
              let data2 = []
              data2 = {
                cityId: options.cityid
              }



              let callBack = (res2) => {
                if (res2 == null) {
                  console.log("网络请求错误！");
                  return;
                }
                if (res2.data.status != 200) {
                  console.log("请求数据错误");
                  return;
                }
                if (res2.data.status === 200) {

                  for (let i = 0; i < res2.data.data.region.length; i++) {
                    if (res2.data.data.region[i].id === parseInt(options.countyid)) {
                      console.log(res2.data.data.region[i].name)
                      self.data.region[2] = res2.data.data.region[i].name
                      console.log('区')
                      self.setData({
                        region: self.data.region
                      })
                    }
                  }
                }
              }
              Api.reqFormPost(url, data2, callBack)
            }
          }
          Api.reqFormPost(url, data1, callBack)
        }
      }
      Api.reqFormPost(url, data, callBack)
      console.log(options)
      let idList = []
      idList.push(options.provinceid)
      idList.push(options.cityid)
      idList.push(options.countyid)
      let def = false
      if (options.isdefault === '1') {
        def = true
      }
      this.setData({
        addressid: options.addressid,
        contactname: options.contactname,
        contactmobile: options.contactmobile,
        address: options.address,
        isdefault: def,
        idList: idList,
        initDefalut: def
      })
    }
    
  },

  picChange(e) {
    console.log(e.detail.value)
    this.setData({
      region: e.detail.value,
    })
  },
  ifHaveDefauleAddress() {
    let self = this
    wx.request({
      method: 'post',
      url: app.globalData.baseUrl1 + '/address/defaultaddress',
      data: {
        token: app.globalData.token,
        userId: app.globalData.userId
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded' // 默认值
      },
      success: function (res) {
        self.setData({ hasGoneAway: false })
        
        console.log(22, res.data.data)
        if (!res.data.data.address) {
          self.setData({
            isdefault: true
          })
        }
        self.save()
      }
    })

  },
  save() {


    //判断是否没有默认地址  自动设置 this.data.isdefault === false






    if (this.data.pagetype === 'edit') {
      console.log(this.data.idList)
      let self = this
      let url = app.globalData.baseUrl1 + '/address/update';
      let data = {
        token: app.globalData.token,
        userId: app.globalData.userId,
        addressId: this.data.addressid,
        provinceId: this.data.idList[0],
        cityId: this.data.idList[1],
        countryId: this.data.idList[2],
        address: this.data.address,
        contactName: this.data.contactname,
        contactMobile: this.data.contactmobile,
        isDefault: this.data.isdefault
      }
      let callBack = (res) => {

        if (res == null) {

          console.log("网络请求错误！");
          return;
        }
        if (res.data.status != 200) {
          console.log("请求数据错误");
          return;
        }


        if (!self.data.hasGoneAway) {
          self.setData({ hasGoneAway: true })

        wx.navigateBack({
          delta: 1
        })

        }
      }
      Api.reqFormPost(url, data, callBack)
    } else {



      let url = app.globalData.baseUrl1 + '/address/add';

      let data = {
        token: app.globalData.token,
        userId: app.globalData.userId,
        provinceId: this.data.idList[0],
        cityId: this.data.idList[1],
        countryId: this.data.idList[2],
        address: this.data.address,
        contactName: this.data.contactname,
        contactMobile: this.data.contactmobile,
        isDefault: this.data.isdefault
      }
      let self = this

      let callBack = (res) => {

        console.log(res)
        if (res == null) {

          console.log("网络请求错误！");
          return;
        }

        if (res.data.status != 200) {
          console.log("请求数据错误");
          return;
        }

        if (!self.data.hasGoneAway) {
          self.setData({ hasGoneAway: true })
        wx.navigateBack({
          delta: 1
        })
        }
      }
      Api.reqFormPost(url, data, callBack)
    }

  },
  isdefault(e) {
    if (this.data.initDefalut){
      return
    }
    this.setData({
      isdefault: !this.data.isdefault
    })
  },

  bindRegionChange: function (e) {
    let self = this

    if (e.detail.column == 0) {
      console.log(this.data.range[e.detail.column][e.detail.value].name)
      wx.request({
        method: 'post',
        url: app.globalData.baseUrl1 + '/address/querycity',
        data: {
          provinceId: this.data.range[e.detail.column][e.detail.value].id
        },
        header: {
          'content-type': 'application/x-www-form-urlencoded' // 默认值
        },
        success: function (res) {
          console.log(1, res)

          self.data.range[1] = res.data.data.region



          self.setData({
            range: self.data.range
          })

     

        }
      })

    } else if (e.detail.column == 1) {
      wx.request({
        method: 'post',
        url: app.globalData.baseUrl1 + '/address/querycountry',
        data: {
          cityid: this.data.range[e.detail.column][e.detail.value].id
        },
        header: {
          'content-type': 'application/x-www-form-urlencoded' // 默认值
        },
        success: function (res1) {
          let range = self.data.range
          range[2] = res1.data.data.region
          self.setData({
            range: range,
            twoIndex: e.detail.value
          })
          wx.hideLoading()
        }
      })
    }
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    if (app.globalData.merchant === null) {
      return
    } 
    if (app.globalData.merchant.mustLogin || app.globalData.userId === null) {
      if (app.globalData.userId === null) {
      wx.navigateTo({
        url: '/pages/core/login/login',
        success() {
          wx.showToast({
            title: '请先登陆',
            icon: 'loading',
            duration: 1000
          })
        }
      })
      return
    }}
    let self = this

    this.setData({ hasGoneAway: false })
    if (this.data.pagetype =='edit'){
      wx.setNavigationBarTitle({
        title: '修改地址'
      })
    }else{
      wx.setNavigationBarTitle({
        title: '新增地址'
      })
    }
    
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})